<script setup lang="ts">
import {onMounted, ref, toRaw} from "vue";
import axios from "axios";
import {ElNotification} from "element-plus";
import {ServerHost} from "@/main.js";
import {Refresh, Search, Timer} from "@element-plus/icons-vue";
import dayjs from 'dayjs'
import PostOrEditPolicy from "@/components/policyManage/PostOrEditPolicy.vue";

const policyList = ref([])
const isLoadingList = ref(true)
const isEditDialogVisible = ref(false)
const selectedPolicy = ref()

// 懒加载政策列表
const observerDiv = ref(null)
const hasLoad = ref(false)
onMounted(() => {
  const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        if (!hasLoad.value) {
          loadList()
        }
      }
    });
  });
  observer.observe(observerDiv.value);
})

const loadList = () => {
  console.log("开始获取政策列表")
  axios.get(`${ServerHost}/getPolicyList?key=${searchKey.value}`)
      .then((res) => {
        if (res.status === 200) {
          ElNotification({
            title: '政策获取成功',
            type: 'success',
            position: 'bottom-right',
          })
          policyList.value = res.data;
          hasLoad.value = true
          isLoadingList.value = false
        } else {
          ElNotification({
            title: '政策获取失败',
            type: 'error',
            position: 'bottom-right',
          })
        }
      })
}

// const onEditPolicy = (id: string) => {
//   console.log(id)
// }

const onRowClick = (row: any, column: any, event: Event) => {
  isEditDialogVisible.value = true

  // selectedPolicy.value = policyList.value.find((Policy: any) => {
  //   return Policy.id === row.id
  // })
  policyList.value.forEach((policy: any) => {
    if (policy.id === row.id) {
      // 深拷贝policy，防止子组件修改父组件数据
      selectedPolicy.value = structuredClone(toRaw(policy))
    }
  })
}

// watch(policyList, (newValue, oldValue) => {
//   console.log("数据变化了", newValue, oldValue);
// }, { deep: true });


const getIsSubmitDone = (value: string) => {
  isEditDialogVisible.value = !value
  loadList()
}

const searchKey = ref("")

const onSearchKeydown = (event: KeyboardEvent) => {
  if (event.key === "Enter") {
    onSearch()
  }
}

const onSearch = () => {
  if (searchKey.value !== "") {
    loadList()
  }
}

const onClearSearch = (id: string) => {
  loadList()
}


</script>

<template>
  <div ref="observerDiv"/>
  <!--  忽略warn type="search" -->
  <el-input type="text" v-model="searchKey" @keydown="onSearchKeydown" class="mb-2" placeholder="搜索政策"
            :prefix-icon="Search" clearable @clear="onClearSearch">
    <template #append>
      <el-button :icon="Search" @click="onSearch"/>
    </template>
  </el-input>
  <el-tag type="info" class="w-full">点击政策以编辑</el-tag>
  <!--  Table-->
  <!-- height: 减去导航栏、页脚、搜索栏等元素的高度 -->
  <el-table
      :data="policyList"
      height="calc(100vh - 120px - 140px)"
      empty-text="没有政策"
      v-loading="isLoadingList"
      :onRowClick="onRowClick">
    <el-table-column
        prop="postTime"
        label="发布时间"
    >
      <template #default="row">
        <div class="flex items-center">
          <el-icon>
            <timer/>
          </el-icon>
          <!--  格式化日期  -->
          <p>{{ dayjs(row.row.postTime).format('YY/MM/DD HH:mm:ss') }}</p>
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="title" label="标题"/>
    <!--  操作按钮列  -->
    <el-table-column>
      <template #header>
        <el-button type="primary" @click="loadList" :icon="Refresh"/>
      </template>
      <!--          <template #default="row">-->
      <!--            <el-button type="primary" @click="onEditPolicy(row.row.id)">修改</el-button>-->
      <!--          </template>-->
    </el-table-column>
  </el-table>

  <!-- Edit Dialog -->
  <el-dialog
      v-model="isEditDialogVisible"
      title="编辑政策"
      width="500">
    <PostOrEditPolicy type="edit" @getValue="getIsSubmitDone" :policy="selectedPolicy"
                      :key="selectedPolicy"/>
  </el-dialog>
</template>

<style scoped lang="scss">
.el-table .el-table.row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

</style>
